package middleware

import (
	"gin-demo/common"
	"gin-demo/model"
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func AuthMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 获取authorization header
		tokenString := ctx.GetHeader("Authorization")

		//校验token的格式
		if tokenString == "" || !strings.HasPrefix(tokenString, "Bearer ") {
			ctx.JSON(http.StatusUnauthorized, gin.H{"code":401,"msg":"权限不足"})
			ctx.Abort()//抛弃掉请求
			return
		}

		tokenString = tokenString[7:]
		token, claims, err := common.ParseToken(tokenString)
		if err != nil || !token.Valid {
			ctx.JSON(http.StatusUnauthorized, gin.H{"code":401,"msg":"权限不足"})
			ctx.Abort()//抛弃掉请求
			return
		}

		//验证通过， 获取claims中的userid
		userId := claims.UserId
		db := common.GetDB()
		var user model.User
		db.First(&user, userId)

		//yonghu
		if user.ID == 0 {
			ctx.JSON(http.StatusUnauthorized, gin.H{"code":401,"msg":"权限不足"})
			ctx.Abort()//抛弃掉请求
			return
		}
		//用户存在
		//user信息写入上下文,这里的user是个对象
		ctx.Set("user", user)
		ctx.Next()
	}
}
